from flask_appbuilder import ModelView
from flask_appbuilder.fieldwidgets import Select2Widget
from flask_appbuilder.models.sqla.interface import SQLAInterface
from app.models import SerialPortCategory, SerialPort, ResisterRange, Selector, Profile, Tray, CheckUnit
from wtforms.ext.sqlalchemy.fields import QuerySelectField
from app import appbuilder, db

def query_profile():
    return db.session.query(Profile)


def query_tray():
    return db.session.query(Tray)


def query_resister_range():
    return db.session.query(ResisterRange)


class SelectorView(ModelView):
    datamodel = SQLAInterface(Selector)

    list_columns = ['name', 'profile.name', 'tray.name', 'resister_a.name', 'resister_b.name', 'weight', 'readme']
    edit_form_extra_fields = {'profile': QuerySelectField('Profile',
                                                          query_factory=query_profile,
                                                          widget=Select2Widget(extra_classes="readonly")),
                              'tray': QuerySelectField('Tray',
                                                          query_factory=query_tray,
                                                          widget=Select2Widget(extra_classes="readonly")),
                              'resister_a': QuerySelectField('ResisterA',
                                                       query_factory=query_resister_range,
                                                       widget=Select2Widget(extra_classes="readonly")),
                              'resister_b': QuerySelectField('ResisterB',
                                                             query_factory=query_resister_range,
                                                             widget=Select2Widget(extra_classes="readonly"))}

    show_template = 'Selector/show_cascade.html'
    add_template = 'Selector/add.html'
    edit_template = 'Selector/edit.html'

class ResisterRangeView(ModelView):
    datamodel = SQLAInterface(ResisterRange)
    related_views = [SelectorView]
    list_columns = ['name', 'min', 'max', 'readme']


appbuilder.add_view(SelectorView, "Selectors", icon="fa-folder-open-o", category="Company")
# appbuilder.add_separator("Company")
appbuilder.add_view(ResisterRangeView, "Resisters", icon="fa-folder-open-o", category="Company")

